package com.gt.aep.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gt.aep.base.config.DataConfig;
import com.gt.aep.base.entity.systemManage.SysPermission;
import com.gt.aep.base.entity.systemManage.SysUser;
import com.gt.aep.base.entity.util.Result;
import com.gt.aep.base.service.systemManage.SysPermissionService;
import com.gt.aep.base.service.systemManage.SysUserService;
import com.gt.aep.base.util.EncryptUtil;
import com.gt.aep.base.util.PermUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
@RequestMapping("/")
public class LoginController {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysPermissionService sysPermissionService;
    @Autowired
    DataConfig dataConfig;
    @Autowired
    PermUtil permUtil;

    @RequestMapping("ajaxLogin")
    @ResponseBody
    public Map<String, Object> login(String data, String encryptAesKey){
//        //解密前端发送过来的数据
//        Map<String, Object> decData = EncryptUtil.decode(data,encryptAesKey);
//        String jsAesKey = (String) decData.get("jsAesKey");
//        String decrypt = (String) decData.get("data");
//        //将String类型数据转化为对象
//        JSONObject dataObject = new JSONObject(JSONObject.parseObject(decrypt));
//        //根据前端的字段获取相对应的属性
//        String jsPublicKey = (String) dataObject.get("jsPublicKey");
//        String userName = (String) dataObject.get("userName");
//        String password = (String) dataObject.get("password");
        String userName = null;
        String password = null;


        Session session = SecurityUtils.getSubject().getSession();

        try {
            UsernamePasswordToken token=new UsernamePasswordToken(userName,password);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);

            dataConfig.setUserPermission(permUtil.getUserPermission());
//            return "redirect:/go/index";
            return Result.success("登录成功");
        }catch (Exception e){
            e.printStackTrace();
            return  Result.error("帐号或者密码错误");
        }
    }



    @RequestMapping("logout")
    @ResponseBody
    public Map<String, Object> logout(HttpServletResponse response, HttpServletRequest request){
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Result.success("url","Login.html");
    }


    @RequestMapping("getMenu")
    @ResponseBody
    public Map<String, Object> index(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        dataConfig.getPermList().clear();
        for(Map<String,Object> permNo:dataConfig.getUserPermission())
        {
            dataConfig.getPermList().add(permNo.get("permNo").toString());
        }
        Subject subject = SecurityUtils.getSubject();
        SysUser user = (SysUser) subject.getSession().getAttribute("userKey");
        if(user == null){
            System.out.println("当前无登陆用户，退出！");
            return Result.error();
        }else{
            String id = user.getId();
            Map<String, Object> menuMap = new HashMap<>();
            /**
             * 获取菜单列表
             * 根据权限设置菜单是否显示
             * */
            QueryWrapper<SysPermission> wrapper = new QueryWrapper<>();
            wrapper.eq("isMenu",1).orderByAsc("permNo");

            List<Map<String, Object>> menuLevelOne = new ArrayList<>();
            List<Map<String, Object>> menuLevelTow = new ArrayList<>();
            List<Map<String, Object>> menuLevelThree = new ArrayList<>();
            List<Map<String, Object>> maps = sysPermissionService.listMaps(wrapper);
            for (Map<String, Object> map : maps) {

                QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("permNo", map.get("permNo"));
                List<SysPermission> permissionList = sysPermissionService.list(queryWrapper);

                if (map.get("level").equals(1)&&map.get("isMenu").equals(1)&&dataConfig.getPermList().contains(permissionList.get(0).getPermNo())) {
                    menuLevelOne.add(map);
                } else if (map.get("level").equals(2)&&map.get("isMenu").equals(1)&&dataConfig.getPermList().contains(permissionList.get(0).getPermNo())) {
                    menuLevelTow.add(map);
                } else if (map.get("level").equals(3)&&map.get("isMenu").equals(1)&&dataConfig.getPermList().contains(permissionList.get(0).getPermNo())) {
                    menuLevelThree.add(map);
                }
            }
            menuMap.put("menuLevelOne", menuLevelOne);
            menuMap.put("menuLevelTow", menuLevelTow);
            menuMap.put("menuLevelThree", menuLevelThree);
            return menuMap;
        }


    }

@RequestMapping("getUserInfo")
@ResponseBody
public String getUser(String data, String encryptAesKey) {
    //解密前端发送过来的数据
    Map<String, Object> decData = EncryptUtil.decode(data,encryptAesKey);
    String jsAesKey = (String) decData.get("jsAesKey");
    String decrypt = (String) decData.get("data");
    //将String类型数据转化为对象
    JSONObject dataObject = new JSONObject(JSONObject.parseObject(decrypt));
    //根据前端的字段获取相对应的属性
    String jsPublicKey = (String) dataObject.get("jsPublicKey");
    String userName = (String) dataObject.get("userName");
    String permPrefix = (String) dataObject.get("permPrefix");

    Map<String,Object> map=new LinkedHashMap<>();
    //根据userName获取该用户的基本信息和角色信息
    map.put("userInfo",sysUserService.getUserRoleInfo(userName));
    map.put("permList",dataConfig.getPermList());
    return JSON.toJSONString(Result.success(map));

}

}
